﻿/*****************************************************************************\
 *             University of Illinois/NCSA Open Source License
 *
 * 
 *      Copyright © 2012,2013, The Board of Trustees of the University of Illinois. All rights reserved.
 *
 *      Developed by: Rakesh Bobba, Derek Dagit, Erich Heine, Denis Kholine,
 *                    Klara Nahrstedt, David Rodgers,   William H. Sanders, Tim Yardley
 *
 *      Information Trust Institute/Coordinated Science Laboratory
 * 
 *      University of Illinois
 *      
 *      The Board of Trustees of the University of Illinois
 *      109 Coble Hall
 *      801 South Wright Street
 *      Champaign, IL 61820-6242
 *
 *      http://www.iti.illinois.edu / http://csl.illinois.edu
 * 
 *      Permission is hereby granted, free of charge, to any person obtaining a copy of this software and 
 *      associated documentation files (the “Software”), to deal with the Software without restriction, 
 *      including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *      and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
 *      subject to the following conditions:
 *
 *      Redistributions of source code must retain the above copyright notice, this list of conditions and the
 *      following disclaimers.
 *      
 *      Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
 *      the following disclaimers in the documentation and/or other materials provided with the distribution.
 *
 *      Neither the names of Information Trust institute, Coordinated Science Laboratory, University of Illinois,
 *      The Board of Trustees of the University of Illinois nor the names of its contributors may be used to 
 *      endorse or promote products derived from this Software without specific prior written permission.
 *      
 *      THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
 *      LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN
 *      NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 *      WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 
 *      SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE SOFTWARE.
 *      
 \*****************************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using Disruptor;

namespace SIEGate.Core.MessageBusses
{
    class RingBufferMessageBusConsumer
    {
        private RingBufferMessageBus _mb;
        private ISequenceBarrier _frontBarrier;
        private Sequence _whereAmI = new Sequence(Sequencer.InitialCursorValue);
        internal TimeSpan m_waittimeout = new TimeSpan(10 * 1000 * 2);
        public ISet<Guid> StreamIDs { get; private set; }
        public Sequence Sequence
        {
            get { return _whereAmI; }
        }
        public IMeasurement Recv()
        {
            if (!StreamIDs.Any()) { return null; }
            while (true)
            {
                long recSeq = _whereAmI.Value + 1L;
                _frontBarrier.WaitFor(recSeq);
                IMeasurement res = null;
                while (res == null) res = _mb.RingBuffer[recSeq].data;
                _whereAmI.LazySet(recSeq);
                if (StreamIDs.Contains(res.StreamID))
                {
                    return res;
                }
            }
        }

        public IMeasurement[] RecvMany(int max)
        {
            // NOTE we need sanity code for long wraps in sequences,  however at 2million
            // measurements per second through the buffer it would take almost 30K years to wrap the long.....
            long nextSeq = _whereAmI.Value + 1L;

            // WaitFor with a timeout will return a value < nextSeq if it times out
            // in that case we got nothing, so just be done.
            long actualSeq = _frontBarrier.WaitFor(nextSeq, m_waittimeout);
            if (actualSeq < nextSeq)
            {
                return new IMeasurement[0];
            }

            int asize;

            if (max != 0)
            {
                asize = max;
            }
            else
            {
                asize = (int)(actualSeq - _whereAmI.Value);
            }

            int i = 0;
            IMeasurement m;
            // prolly won't fill, could, so just avoid resize
            List<IMeasurement> res = new List<IMeasurement>(asize);
            // this will stop filling values at max size or the front of the queue, whatever comes first.
            while (nextSeq <= actualSeq && i < asize)
            {
                while (true)
                {
                    m = _mb.RingBuffer[nextSeq].data;
                    if (m != null) break;
                }
                if (StreamIDs.Contains(m.StreamID))
                {
                    res.Add(m);
                    i++;
                }
                nextSeq++;
            }
            _whereAmI.LazySet(nextSeq - 1L);
            //are arrays stack or reference type for return. do we want to do list or IEnumberable instead?
            return res.ToArray<IMeasurement>();
        }

        public void Enable()
        {
            _mb.StartConsumer(this);
        }
        public void Disable()
        {
            _mb.PauseConsumer(this);
        }

        public RingBufferMessageBusConsumer(ISet<Guid> streamIDs, RingBufferMessageBus mb, ISequenceBarrier front, long startseq)
        {
            StreamIDs = streamIDs;
            _mb = mb;
            _frontBarrier = front;
            _whereAmI.LazySet(startseq);
        }
    }
}
